#include "stdio.h"
#include<WINSOCK2.h>
#include<string>
#include<iostream>
#include<tchar.h>
#pragma comment(lib,"WS2_32.lib")
#define BUF_SIZE 64
#define IP "192.168.0.104"
//设置头文件，库文件与常量（缓冲区大小）

int _tmain(int argc, _TCHAR* argv[])
{
	WSADATA wsd;
	SOCKET sHost;
	SOCKADDR_IN servAddr;
	char buf[BUF_SIZE];
	int retVal;
	//声明程序所需的变量

	if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
	{
		printf("WSAStartup failed! \n");
		return 1;
	}
	//初始化Socket环境

	sHost = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (INVALID_SOCKET == sHost)
	{
		printf("socket failed! \n");
		WSACleanup();
		return -1;
	}
	//创建client端的Socket

	servAddr.sin_family = AF_INET;
	servAddr.sin_addr.S_un.S_addr = inet_addr(IP);
	servAddr.sin_port = htons(9990);
	int sServerAddlen = sizeof(servAddr);
	//设置服务器socket地址

	retVal = connect(sHost, (LPSOCKADDR)&servAddr, sizeof(servAddr));
	if (retVal == SOCKET_ERROR)
	{
		printf("connect failed!\n");
		closesocket(sHost);
		WSACleanup();
		return -1;
	}
	//连接到服务器

	while (1)
	{
		printf("请输入传递给服务器端的信息：");
		std::string str; //向服务器端发送数据
		std::getline(std::cin, str);
		ZeroMemory(buf, BUF_SIZE);
		strcpy(buf, str.c_str());//将输入的数据复制到buf区域
		retVal = send(sHost, buf, strlen(buf), 0);
		if (SOCKET_ERROR == retVal)
		{
			printf("send failed! \n");
			closesocket(sHost);
			WSACleanup();
			return -1;
		}//send 函数debug
		retVal = recv(sHost, buf, sizeof(buf), 0);
		if (SOCKET_ERROR == retVal)
		{
			printf("recv failed! \n");
			closesocket(sHost);
			WSACleanup();
			return -1;
		}//recv 函数debug
		printf("Recv From Server: %s\n", buf);//接受服务器回传数据
		/*if ((buf[1] == '2' && buf[2] > '6') || buf[1] > '2')
		{
			printf("WARNING! Abnormal temperature, please check\n ");
		}*/
		//温度检测，若超过37则报警
		if (strcmp(buf, "quit") == 0)
		{
			printf("quit! \n");
			break;
		}
	}
	//服务器与客户端通信部分

	closesocket(sHost);
	WSACleanup();
	system("pause");
	return 0;
}